import {
  Drawer,
  Modal,
  Input,
  Button,
  Space,
  message,
  Layout,
  Dropdown,
  MenuProps,
  Menu,
} from 'antd';
import React, { useState, useEffect, useRef } from 'react';

import userService from '@/api/services/userService';
import { SvgIcon } from '@/components/icon';
import Back from '@/components/router/Back';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useRouter } from '@/router/hooks';

import PermissionTable from './components/PermissionTable';
import PermissionTree from './components/PermissionTree';
import './styles/permissionTable.css';

import { SettingOutlined } from '@ant-design/icons';
import RouterMenu from '../components/menus/RouterMenu';
import { useUserInfo } from '@/store/userStore';
import useInitialize from '@/hooks/event/use-initialize';
import { useManagePage } from '@/store/configStore';
import { useRoleManage } from '@/store/roleManageStore';
import { Role } from '@/types/role';
import usePermission from '@/hooks/event/usePermission';

interface PermissionDrawerProps {
  visible?: boolean;
  onClose?: () => void;
}

const { Header } = Layout;

const PermissionDrawer: React.FC<PermissionDrawerProps> = ({ visible, onClose }) => {
  const { isInManager } = usePermission();
  const [modalVisible, setModalVisible] = useState(false);
  const [roleName, setRoleName] = useState('');
  const [roleDescription, setRoleDescription] = useState('');
  const { isEnableRoleConditions } = useRoleManage();
  // const isEnableRoleConditions = false
  const [showRoleConfirm, setShowRoleConfirm] = useState(false);
  const [displayRoleList, setDisplayRoleList] = useState([]);
  const [userRolePermissionList, setUserRolePermissionList] = useState([]);
  const { role: userRole } = useUserInfo();

  const managePage = useManagePage();

  const router = useRouter();

  const { isPc } = useWindowWidth();

  const [roleNameList, setRoleNameList] = useState<string[]>([]);
  const [roleSelected, setRoleSelected] = useState<string>('');
  const [roleSelectedConfirm, setRoleSelectedConfirm] = useState<string>('');

  const menu = (
    <Menu selectedKeys={[roleSelectedConfirm]}>
      {roleNameList.map((role) => (
        <Menu.Item
          key={role.code}
          onClick={() => {
            setRoleSelected(role.code);
            setShowRoleConfirm(true);
          }}
        >
          {role.name}
        </Menu.Item>
      ))}
    </Menu>
  );

  const validateForm = () => {
    let isValid = true;

    if (!roleName) {
      message.error('角色名称不能为空');
      isValid = false;
    }

    if (!roleDescription) {
      message.error('角色描述不能为空');
      isValid = false;
    }

    return isValid;
  };

  const handleAddRole = () => {
    setModalVisible(true);
  };

  const handleModalClose = () => {
    setRoleName('');
    setRoleDescription('');
    setModalVisible(false);
  };

  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }
    const parentRole: Role = userRolePermissionList?.filter(
      (r: Role) => r?.code === roleSelectedConfirm,
    )?.[0];
    const newRole = await userService.addRole({
      name: roleName,
      description: roleDescription,
      ...(parentRole && { parent_id: parentRole.id }),
    });
    message.success('新增角色成功');

    setRoleName('');
    setRoleDescription('');
    setModalVisible(false);

    // if (isPc) {
    //   const newRoleList = [...displayRoleList, newRole];
    //   console.log(newRoleList);
    //   permissionTableRef.current && permissionTableRef.current.updateRoleList(newRoleList);
    // }
    if (permissionTreeRef.current) {
      permissionTreeRef.current.getRoleList(newRole);
    } else {
      if (displayRoleList.length >= 4) {
        // 如果 displayRoleList 长度大于等于 4，替换掉最后一个元素
        setDisplayRoleList([...displayRoleList.slice(0, -1), newRole]);
      } else {
        // 否则直接添加新角色
        setDisplayRoleList([...displayRoleList, newRole]);
      }
    }
  };

  useEffect(() => {
    !modalVisible &&
      !showRoleConfirm &&
      permissionTableRef.current &&
      permissionTableRef.current.updateRoleList(displayRoleList);
  }, [displayRoleList]);

  const permissionTableRef = useRef<any>(null);
  const permissionTreeRef = useRef<any>(null);

  const roleSelect = (roleList) => {
    console.log(roleList);
    setDisplayRoleList(roleList);
    if (!isPc && permissionTableRef.current) {
      permissionTableRef.current.updateRoleList(roleList);
      setRoleSelectedConfirm(roleSelected);
      setShowRoleConfirm(false);
    }
  };

  useEffect(() => {
    userService.getRolePermissions().then((res) => {
      console.log(res);
      setUserRolePermissionList(res);
      const userData = res.filter((i) => i?.id == userRole?.id).slice(0, 1);
      isPc && setDisplayRoleList(userData);

      const roles = res
        .filter((i) => userRole?.code.includes(i?.code) || userRole?.code == i?.code)
        .map((item: Role) => ({
          code: item.code,
          name: item.name,
          id: item.id
        }))
        .filter((item, index, self) =>
          index === self.findIndex(i => i.code === item.code)
        );

      setRoleNameList(roles);

      if (res.length > 1) {
        // 设置默认选中的第一个角色
        const defaultRole = roles[0]?.code;
        setRoleSelected(defaultRole);
        setRoleSelectedConfirm(defaultRole);
      }
    });

  }, []);

  const roleRefresh = () => {
    console.log(displayRoleList);
    if (permissionTableRef.current) {
      permissionTableRef.current.updateRoleList(displayRoleList);
    }
  };

  const roleUpdate = () => {
    if (permissionTreeRef.current) {
      permissionTreeRef.current.getRoleList();
    }
  };

  return (
    <>
      <Layout className="h-full" style={{ background: '#FBFCFF', overflowX: 'hidden' }}>
        <Header style={{ background: '#FBFCFF', padding: 0, borderBottom: '1px solid #DDE5FF' }}>
          <div className="flex items-center">
            <div className="flex">
              {!isInManager && <Back
                title={'返回'}
                onClick={() => {
                  // router.back();
                  router.push(managePage);
                }}
              />}
              {/* {isPc && (
                <div
                  style={{
                    width: '2px',
                    height: '20px',
                    backgroundColor: '#8b8282',
                    marginLeft: '20px',
                    marginTop: '24px',
                  }}
                />
              )}
              <RouterMenu /> */}
            </div>
            <div className="ml-auto" style={{ display: 'flex', paddingRight: '30px' }}>
              {roleNameList?.length > 1 ? (
                <Dropdown overlay={menu} trigger={['hover']}>
                  <div
                    style={{
                      fontSize: '14px',
                      fontWeight: 400,
                      color: '#474C5F',
                      display: 'flex',
                      alignItems: 'center',
                      marginRight: '20px',
                    }}
                  >
                    <SettingOutlined style={{ paddingRight: '5px' }} />
                    <span className="truncate">权限配置</span>
                  </div>
                </Dropdown>
              ) : (
                <div
                  style={{
                    fontSize: '14px',
                    fontWeight: 400,
                    color: '#474C5F',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    marginRight: '20px',
                  }}
                  onClick={() => {
                    setShowRoleConfirm(true);
                  }}
                >
                  <SettingOutlined style={{ paddingRight: '5px' }} />
                  <span className="truncate">权限配置</span>
                </div>
              )}

              {!isEnableRoleConditions && (
                <div
                  style={{
                    fontSize: '14px',
                    fontWeight: 400,
                    color: '#474C5F',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                  }}
                  onClick={handleAddRole}
                >
                  <SvgIcon icon="ic_rj_plus" size="16" />
                  <span className="truncate">新增角色</span>
                </div>
              )}
            </div>
          </div>
        </Header>

        <div style={{ background: '#FBFCFF', width: '100%', padding: isInManager ? '0 20px 20px 20px' : '20px', overflow: 'auto' }}>
          <PermissionTable ref={permissionTableRef} onRoleRefresh={roleUpdate} roleSelected={roleSelected} />
        </div>
      </Layout>

      <Modal
        className="permission-modal"
        title={
          // <div style={{ textAlign: 'left', color: '#414141', fontSize: '19px' }}>
          //   权限配置
          // </div>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              margin: '0 20px',
              backgroundColor: '#ECEFF7',
            }}
          >
            <span
              style={{
                textAlign: 'left',
                color: '#414141',
                fontSize: '19px',
              }}
            >
              权限配置
            </span>
            <span
              style={{
                fontSize: '12px',
                fontWeight: 800,
                alignContent: 'end',
                paddingRight: '10px',
                // color: 'rgb(142, 147, 164)',
                color: '#6640FF',
              }}
            >
              选择角色配置权限
            </span>
          </div>
        }
        open={showRoleConfirm}
        width={isPc ? '50%' : '80%'}
        onCancel={() => {
          setRoleSelected(roleSelectedConfirm)
          setShowRoleConfirm(false);
        }}
        closable={false}
        footer={
          isPc ? (
            <div style={{ textAlign: 'end', marginRight: '20px' }}>
              <Space size={20}>
                <Button
                  onClick={() => {
                    setRoleSelected(roleSelectedConfirm)
                    setShowRoleConfirm(false);
                  }}
                >
                  取消
                </Button>
                <Button
                  key="submit"
                  type="primary"
                  onClick={() => {
                    setShowRoleConfirm(false);
                    setRoleSelectedConfirm(roleSelected);
                    roleRefresh();
                  }}
                >
                  确定
                </Button>
              </Space>
            </div>
          ) : (
            false
          )
        }
      >
        <PermissionTree
          initSelected={displayRoleList}
          onRoleRefresh={roleSelect}
          roleSelected={roleSelected}
          ref={permissionTreeRef}
        />
      </Modal>

      <Modal
        title={<div style={{ textAlign: 'center' }}>新增角色</div>}
        open={modalVisible}
        closable={false}
        width={300}
        onCancel={handleModalClose}
        footer={
          <div style={{ textAlign: 'center' }}>
            <Space size={56}>
              <Button onClick={handleModalClose}>取消</Button>
              <Button key="submit" type="primary" onClick={handleSubmit}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div style={{ marginBottom: '16px' }}>
          <Input
            value={roleName}
            onChange={(e) => setRoleName(e.target.value)}
            placeholder="请输入角色名称"
          />
        </div>
        <div>
          <Input.TextArea
            value={roleDescription}
            onChange={(e) => setRoleDescription(e.target.value)}
            style={{ resize: 'none' }}
            placeholder="请输入角色描述"
            rows={4}
          />
        </div>
      </Modal>
    </>
  );
};

export default PermissionDrawer;
